Golang
Golang表單的部分,需要使用兩個檔案的方案來demo
首先在資料夾中隨意建立一個.html結尾的檔案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>表單</title>
</head>
<body>
<form action="http://localhost:8000/" method="get">
<p>First name: <input type="text" name="first name" /></p>
<p>Last name: <input type="text" name="last name" /></p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
要注意的是action 必須跟你下一個步驟的golang檔案所開的url是相呼應的,所以如果跑起來沒反應,注意一下port是不是相同
package main
import (
"fmt"
"log"
"net/http"
)
func GetForm(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
for k, v := range r.Form {
fmt.Println("key is: ", k)
fmt.Println("val is: ", v)
fmt.Fprintf(w, "key is: %s \n", k)
fmt.Fprintf(w, "val is: %s \n", v)
}
fmt.Fprintf(w, "hello world")
}
func main() {
http.HandleFunc("/", GetForm)
err := http.ListenAndServe("localhost:8000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
這樣我們就簡單地跑了一個簡單的接收HTML表單的程式囉!!
要特別注意的部分是
fmt.Println("key is: ", k)
fmt.Fprintf(w, "key is: %s \n", k)
一個是在終端機上輸出,一個是在瀏覽器上輸出唷!
如果我們要在golang使用json的話,需要引用encodeing/json這個套件
package main
import (
"fmt"
"encoding/json"
)
type response1 struct {
Id int
Os []string
}
func main() {
Page_json := response1 {Id : 2, Os: []string{"windows", "mac", "linux"}}
byteSlice, _ := json.MarshalIndent(Page_json , "", " ")
fmt.Println(string(byteSlice))
}
然後我在網路上還看到類似的寫法(Marshal與MarshalIndent)
res, _ := json.Marshal(Page_json)
fmt.Println(string(res))
res, _ = json.MarshalIndent(Page_json , "", " ")
fmt.Println(string(res))
在Go Playground上跑看看結果一下,看是差異在哪邊?
res, _ := json.Marshal(Page_json)
{"Id":2,"Os":["windows","mac","linux"]}
res, _ = json.MarshalIndent(Page_json , "", " ")
{
"Id": 2,
"Os": [
"windows",
"mac",
"linux"
]
}